package com.xbn.xbnmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xbn.common.constant.CartConstrant;
import com.xbn.common.utils.R;
import com.xbn.xbnmall.cart.feign.ProductFeignService;
import com.xbn.xbnmall.cart.interceptor.CartInterceptor;
import com.xbn.xbnmall.cart.service.CartService;
import com.xbn.xbnmall.cart.vo.Cart;
import com.xbn.xbnmall.cart.vo.CartItem;
import com.xbn.xbnmall.cart.vo.SkuInfoVo;
import com.xbn.xbnmall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author XBN
 * @date 2020/8/14 14:40
 * @email 78742541@qq.com
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
        @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(res))
        {
            //购物车没有商品，则添加商品
            CartItem cartItem=new CartItem();
            //远程查询商品信息
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                R info = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //商品添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuInfo.getSkuId());
                cartItem.setPrice(skuInfo.getPrice());
            }, threadPoolExecutor);

            //远程查询sku商品的组合销售信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, threadPoolExecutor);

            CompletableFuture.allOf(getSkuInfo,getSkuSaleAttrValues).get();
            //将查询的商品信息作为购物车保存到redis中
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
return cartItem;
        }
        else {
            //购物车中已经有了这个商品那么只需要修改商品的数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }



    }

    /*
    * 获取购物车中的某个购物项
    * */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    /*
    * 获取整个购物车
    * */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart=new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null)
        {
            //登陆状态,这里要考虑用户刚刚登陆，可能他的临时购物车里有数据，要对临时购物车和用户
            //购物车进行合并
            String cartKey=CartConstrant.CART_PREFI+userInfoTo.getUserId();
        //判断临时购物车有没有数据
            String tempCartKey=CartConstrant.CART_PREFI + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if(tempCartItems!=null)
            {
                //临时购物车有数据，需要合并
                for (CartItem item: tempCartItems
                     ) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清空临时购物车的数据
                clearCart(tempCartKey);
            }
            //获取登陆后的购物车
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);


        }
        else {//未登录状态
            String cartKey =CartConstrant.CART_PREFI+ userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    /*
    * 获取到购物车
    * */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey="";
        if(userInfoTo.getUserId()!=null)
        {
            //登陆了就用登陆的购物车
        cartKey= CartConstrant.CART_PREFI+userInfoTo.getUserId();
        }
        else {
            //没有登陆就用临时购物车
            cartKey= CartConstrant.CART_PREFI+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        return operations;
    }

    private List<CartItem> getCartItems(String cartKey)
    {
        BoundHashOperations<String, Object, Object> hashOperations = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOperations.values();
        if(values!=null&&values.size()>0)
        {
            List<CartItem> collect = values.stream().map((obj) -> {
                String str= (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
        return collect;
        }
        return null;
    }

    /*
    * 清空购物车数据
    * */
    @Override
    public void clearCart(String cartKey)
    {
      stringRedisTemplate.delete(cartKey);
    }


    /*
    * 勾选购物车选中或者未选中
    * */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),s);
    }

    /*
    * 修改购物车商品数量
    * */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));

    }

    /*
    * 删除购物车的某个商品项
    * */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null)
        {
            return null;
        }
        else {
            String cartKey=CartConstrant.CART_PREFI+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            //过滤一下，只要选中的购物项
            List<CartItem> collect = cartItems.stream().filter(item -> {
              return   item.getCheck();
            })
                    .map(item->{
                        R priceData = productFeignService.getPrice(item.getSkuId());
                        String price= (String) priceData.get("data");
                        //TODO 这里为了方便，没有批量查询，导致多次连接远程服务器并且多次调用数据库
                    item.setPrice(new BigDecimal(price));
                    return item;
                    })
                    .collect(Collectors.toList());
            return collect;
        }

    }
}
